package com.shixianjun.leetcode;

public class _2_两数相加 {
    static public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;

        ListNode head = l1;
        ListNode last = null;

        int bit = 0;
        while (l1 != null || l2 != null) {

            if (l1.next == null && l2 != null) {
                l1.next = l2.next;
                l2.next = null;
            }

            int value1 = l1 == null ? 0 : l1.val;
            int value2 = l2 == null ? 0 : l2.val;

            int result = value1 + value2 + bit;
            bit = result / 10;
            l1.val = result % 10;

            last = l1;
            l1 = l1 == null ? l1 : l1.next;
            l2 = l2 == null ? l2 : l2.next;
        }

        if (bit > 0 && last != null) {
            last.next = new ListNode(bit);
        }

        return head;
    }

    public static void main(String[] args) {

        int[] num1 = {9,9,9,9,9,9,9};
        int[] num2 = {9,9,9,9};
        ListNode list1 = new ListNode(num1);
        ListNode list2 = new ListNode(num2);

        System.out.print(list1);
        System.out.print(list2);

        ListNode result = addTwoNumbers(list1, list2);
        System.out.print(result);
    }
}
